package com.dhcc.hikari.excel.listener;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.dhcc.hikari.controller.NrController;
import com.dhcc.hikari.entity.NurseRevocation;
import com.dhcc.hikari.service.NurseRevocationService;
import com.dhcc.hikari.util.SpringUtil;
import com.dhcc.hikari.util.queue.NrsQueue;

@Component
public class DemoDataListener extends AnalysisEventListener<NurseRevocation> {
    private static final Logger LOGGER = LoggerFactory.getLogger(DemoDataListener.class);
	@Autowired
	private NurseRevocationService nurseRevocationService;
	@Autowired
	NrController nrController;
	long startTime =0;
	long endTime =0;
	long time =0;
	long totalTime = 0;
	int totalCount = 0;
    /**
     * 每隔5条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 10000;
    List<NurseRevocation> list = new ArrayList<NurseRevocation>();

    @Override
    public void invoke(NurseRevocation data, AnalysisContext context) {
    	startTime = System.currentTimeMillis();
//        LOGGER.info("解析到一条数据:{}", JSON.toJSONString(data));
        list.add(data);
        if (list.size() >= BATCH_COUNT) {
        	//改用多线程插入
//        	ThreadPool pool = ThreadManager.getInstance();
//			InsertNrsRunnable myRunnable = new InsertNrsRunnable(list);
//			pool.execute(myRunnable);
//        	try {
//				NrsQueue.getNrsQueue().produce(list);
//			} catch (InterruptedException e) {
//				e.printStackTrace();
//			}
            saveData();
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
        LOGGER.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        LOGGER.info("{}条数据，开始存储数据库！", list.size());
        nrController = (NrController)SpringUtil.getBean("nrController",NrController.class);
//        nurseRevocationService.batchSave(list);
//        nrController.batchSave(list);
        int count = nrController.batchInsert(list);
        LOGGER.info("存储数据库成功！存储："+count+"个");
        endTime = System.currentTimeMillis();
        time = endTime-startTime;
        totalTime +=time; 
        totalCount +=count;
        System.out.println("每次存储数据时间："+time +"--耗时累加："+totalTime+"--累加数值："+totalCount);
    }
}